package com.alinesno.cloud.operation.cmdb.controller.manager;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alinesno.cloud.operation.cmdb.advice.ConvertCode;
import com.alinesno.cloud.operation.cmdb.common.constants.RunerEnum;
import com.alinesno.cloud.operation.cmdb.common.util.RunStringUtils;
import com.alinesno.cloud.operation.cmdb.controller.BaseController;
import com.alinesno.cloud.operation.cmdb.entity.IntegralRecordEntity;
import com.alinesno.cloud.operation.cmdb.entity.UserEntity;
import com.alinesno.cloud.operation.cmdb.repository.UserRepository;
import com.alinesno.cloud.operation.cmdb.service.IntegralService;
import com.alinesno.cloud.operation.cmdb.third.wechat.WechatService;
import com.alinesno.cloud.operation.cmdb.web.bean.JqDatatablesPageBean;
import com.alinesno.cloud.operation.cmdb.web.bean.ResponseBean;
import com.alinesno.cloud.operation.cmdb.web.bean.ResultGenerator;
import com.alinesno.cloud.operation.cmdb.web.bean.UserEntityExt;

/**
 * 后台主面板
 * @author WeiXiaoJin
 * @since 2018年8月14日 下午12:58:05
 */
@Controller
@RequestMapping("/manager/")
public class ManagerMemberController extends BaseController{
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass()) ; 
	
	@Autowired
	private UserRepository userRepository; // 订单详情服务
	
	@Autowired
	private WechatService wechatService ; // 微信服务 
	
	@Autowired
	private IntegralService integralService ; // 积分服务 
	
	@GetMapping("/member_list")
	public String list(Model model) {
 
		createMenus(model); 
		return WX_MANAGER+"member_list";
	}

	/**
	 * 用户积分 
	 * @param model
	 * @param userId
	 * @return
	 */
	@GetMapping("/member_integral")
	public String memberIntegral(Model model , String userId) {
		
		List<IntegralRecordEntity> list = integralService.findIntegralRecord(userId) ; 
		model.addAttribute("list", list) ; 
		
		return WX_MANAGER+"member_integral";
	}
	
	@GetMapping("/member_detail")
	public String memberDetail(Model model , String userId) {
		logger.debug("user id = {}" , userId);
		
		Optional<UserEntity> user = userRepository.findById(userId) ; 
		model.addAttribute("bean", user.get()) ; 
		
		return WX_MANAGER+"member_detail";
	}
	 
	/**
	 * 数据列表
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@ConvertCode
	@ResponseBody
	@GetMapping("/member_list_data")
	public Object memberListData(HttpServletRequest request , Model model , JqDatatablesPageBean page , String runnerStatus) {
		logger.debug("start = {}, size = {} , type = {}" , page.getStart() , page.getLength() , runnerStatus);
		JqDatatablesPageBean p = this.toPage(model, 
				page.buildFilter(UserEntity.class , request)  , 
				userRepository, 
				page); 
		
		p.setData(convertData((List<UserEntity>) p.getData())); 
		return p ; 
	}


	/**
	 * 代码转换
	 * @param data
	 * @return
	 */
	private List<UserEntityExt> convertData(List<UserEntity> data) {
		List<UserEntityExt> dataList = new ArrayList<UserEntityExt>() ; 
		for(UserEntity e: data) {
			UserEntityExt ee = new UserEntityExt() ; 
			BeanUtils.copyProperties(e, ee);
			
			String filedProp = e.getFieldProp() ; 
			if(StringUtils.isNoneBlank(filedProp)) {
				RunerEnum re = RunerEnum.getStatus(filedProp) ; 
				if(re != null) {
					ee.setFieldPropLabel(re.getText());
				}
			}
			
			dataList.add(ee) ;
		}
		return dataList ;
	}
	
	/**
	 * 人员删除
	 * @param id
	 * @param code
	 * @return
	 */
	@ResponseBody
	@GetMapping("/stopMan")
	public ResponseBean<String> stopMan(String id , String code) {
		logger.debug("停止人员{}" , id);
		if(StringUtils.isNoneBlank(id)) {
			RunerEnum r = RunerEnum.getStatus(code) ; 
			if(r != null) {
				Optional<UserEntity> users = userRepository.findById(id) ; 
				if(users.isPresent()) {
					UserEntity u = users.get() ; 
					u.setFieldProp(r.code);
					userRepository.save(u) ; 
					return ResultGenerator.genSuccessMessage(r.text) ; 
				}
			}
		}
		return ResultGenerator.genFailMessage("停止失败.") ; 
	}
	 
	
	/**
	 * 会员申请
	 * @return 
	 */
	@ResponseBody
	@GetMapping("/applyMan")
	public ResponseBean<String> applyMan(String id , String code) {
		logger.debug("申请会员{}" , id);
		if(StringUtils.isNoneBlank(id)) {
			RunerEnum r = RunerEnum.getStatus(code) ; 
			if(r != null) {
				Optional<UserEntity> users = userRepository.findById(id) ; 
				if(users.isPresent()) {
					UserEntity u = users.get() ; 
					boolean isRunman = code.equals(RunerEnum.STATUS_RUNMAN.code)?true:false ; 
					if(isRunman) {
						u.setRealName(u.getRealNameTmpl());
					}
					
					u.setFieldProp(r.getCode());
					userRepository.save(u) ; 
					
					//发送微信通知至申请人员
					wechatService.sendNoticeToApplyMan(u , isRunman) ; 
					return ResultGenerator.genSuccessMessage(r.getText()) ; 
				}
			}
		}
		return ResultGenerator.genFailMessage("申请失败.") ; 
	}
	
	@ResponseBody
	@GetMapping("/changeStatus")
	public ResponseBean<String> changeStatus(String id) {
		logger.debug("change status uid = {}" , id);
		Optional<UserEntity> userOption = userRepository.findById(id) ; 
		
		if(userOption.isPresent()) {
			UserEntity user = userOption.get() ; 
			user.setHasStatus((1+user.getHasStatus())%2);
			userRepository.save(user) ; 
			return ResultGenerator.genFailMessage("修改成功.") ; 
		}
		
		return ResultGenerator.genFailMessage("修改失败.") ; 
	}
	
	@ResponseBody
	@PostMapping("/userRealName")
	public ResponseBean<String> userRealName(String id , String realName , String userRemark) {
		logger.debug("用户id:{} , 姓名:{} , 备注:{}" , id , realName , userRemark);
		
		if(!RunStringUtils.isChinese(realName)) {
			return ResultGenerator.genFailMessage("姓名需中文.") ; 
		}
		
		if(StringUtils.isNoneBlank(id)) {
			Optional<UserEntity> users = userRepository.findById(id) ; 
			if(users.isPresent()) {
				UserEntity u = users.get() ; 
				
				u.setRealName(realName); 
				u.setUserRemark(userRemark); 
				userRepository.save(u) ; 
				
				return ResultGenerator.genSuccessResult(u.getRealName()) ; //+"("+u.getNickname()+")") ; 
			}
		}
		
		return ResultGenerator.genFailMessage("更新用户真实姓名失败.") ; 
	}
	 
}
